package com.leyou.item.service;

/**
 * 商品服务业务层
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional  //开启事务
public class CategoryService extends ServiceImpl<CategoryMapper,  Category> { //继承serviceImpl可以进行批量操作
    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    /**
     * 根据分类父id查询所有分类列表
     * @param pid 父id
     * @return
     */
    public List<Category> findCategoryByPid(Long pid) {
       //封装条件  方式一  [适用性广 可以兼容or条件的查询]
//        QueryWrapper<Category> wrapper = new QueryWrapper<>();
//        wrapper.eq("pid",pid);

        //封装查询条件  方式二 [存在局限性, 查询条件只能是and的关系]
        Category category = new Category();
        category.setParentId(pid);
        QueryWrapper<Category> wrapper = Wrappers.query(category);

        //执行查询条件
//        List<Category> categories = categoryMapper.selectList(wrapper);
        List<Category> categories = super.list(wrapper);  //与上面效果相同,只不过是ServiceImpl对BaseMapper进行了封装,底层一模一样
        //判断是否为空
        if (CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categories;
    }

    /*根据分类id的集合查询分类对象的集合*/
    public List<Category> findCategorysByIds(List<Long> ids) {
        //查询分类对象集合
        List<Category> categoryList = (List<Category>) listByIds(ids);
        //判断分类对象是否存在
        if (CollectionUtils.isEmpty(categoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        return categoryList;
    }

    /*批量查询所有一级分类信息*/
    public List<CategoryDTO> findCategorys() {
        if (!redisTemplate.hasKey("categories")){
            QueryWrapper<Category> wrapper = Wrappers.query();
            List<Category> categories = categoryMapper.selectList(wrapper);
            List<CategoryDTO> categoryDTOS = BeanHelper.copyWithCollection(categories, CategoryDTO.class);
            categoryDTOS.forEach(categoryDTO -> {
                redisTemplate.boundHashOps("categories").put(categoryDTO.getId().toString(), JsonUtils.toString(categoryDTO));
            });
        }
        List<CategoryDTO> categoryDTOList = buildCategoryDTOList(0L);
        return categoryDTOList;
    }

    private List<CategoryDTO> buildCategoryDTOList(Long categoryId) {
        List<Object> categoryStrList = redisTemplate.boundHashOps("categories").values();
        List<CategoryDTO> categoryDTOList = new ArrayList<>();
        categoryStrList.forEach(categoryStr->{
            CategoryDTO categoryDTO = JsonUtils.toBean((String) categoryStr, CategoryDTO.class);
            if (categoryDTO.getParentId().equals(categoryId)){
                categoryDTOList.add(categoryDTO);
            }
        });
        return categoryDTOList;
    }

    /*根据一级分类查询所有子分类*/
    public Map<String, List<String>> findChildCategory(Long categoryId) {
        List<CategoryDTO> categoryDTOList = buildCategoryDTOList(categoryId);
        Map<String, List<String>> categoryMap = new HashMap<>();
        categoryDTOList.forEach(categoryDTO -> {
            List<String> categoryList = new ArrayList<>();
            List<CategoryDTO> categoryDTOChildList = buildCategoryDTOList(categoryDTO.getId());
            categoryDTOChildList.forEach(categoryDTOChild->{
                categoryList.add(categoryDTOChild.getName());
            });
            categoryMap.put(categoryDTO.getName(), categoryList);
        });
        return categoryMap;
    }
}
